﻿using System;
using System.Text;
using System.Windows.Forms;
using System.Threading;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Security.Cryptography;

namespace DATA_SERVER
{
    class Data_Func
    {
        public static MainForm mainfrm;
        private static string LogPath = Application.StartupPath + @"\Log.txt";

        //显示文字
        public static void ShowText(string text)
        {
            string newline = "[" + DateTime.Now + "] " + text;
            MethodInvoker threadappend = delegate()     //以委托的形式
            {
                mainfrm.AddText(newline);   //在主窗口显示文字
                SaveLog(newline);           //存储日志
            };

            mainfrm.BeginInvoke(threadappend);
        }

        //存储日志
        public static void SaveLog(string text)
        {
            string path = Application.StartupPath + "\\Log";//判断文件夹是否存在
            if (!Directory.Exists(path))
            {
                //创建文件夹
                try
                {
                    Directory.CreateDirectory(path);
                }
                catch (Exception e)
                {
                }
            }
            string LogPath1 = Application.StartupPath + "\\Log\\" + DateTime.Now.ToString("yyyy-MM-dd") + "Log.txt";
            FileInfo fi = new FileInfo(LogPath1);
            if (!fi.Exists)
            {
                StreamWriter sw = fi.CreateText();
                sw.WriteLine(text);
                sw.Flush();
                sw.Close();
            }
            else
            {
                StreamWriter sw1 = fi.AppendText();
                sw1.WriteLine(text);
                sw1.Flush();
                sw1.Close();
            }
        }

        //序列化
        public static string Serialize(object data)
        {
            BinaryFormatter formatter = new BinaryFormatter();
            MemoryStream rems = new MemoryStream();
            formatter.Serialize(rems, data);
            return Convert.ToBase64String(rems.GetBuffer());
        }

        //反序列化
        public static object Deserialize(string str)
        {
            byte[] data = Convert.FromBase64String(str);
            BinaryFormatter formatter = new BinaryFormatter();
            MemoryStream rems = new MemoryStream(data);
            return formatter.Deserialize(rems);
        }

        //计算MD5码
        public static string MD5(string encryptString)
        {
            byte[] result = Encoding.Default.GetBytes(encryptString);
            MD5 md5 = new MD5CryptoServiceProvider();
            byte[] output = md5.ComputeHash(result);
            string encryptResult = BitConverter.ToString(output).Replace("-", "");
            return encryptResult;
        }
    }
}
